package com.ns.core.sentinel;

import com.ns.core.utils.sg.IpUtil;
import com.ns.core.utils.sg.ResultError;
import com.ns.core.utils.sg.ResultOk;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;

/**
 * 自定义切面
 *
 * @author lw
 * @since 2023/10/14
 */
@Aspect
@Component
public class RateLimiterAspect {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisScript<Long> limitScript;

    @Before("@annotation(rateLimiter)")
    public void doBefore(JoinPoint point, RateLimiter rateLimiter) {
        String key = rateLimiter.key();
        int time = rateLimiter.time();
        int count = rateLimiter.count();
        Long number;
        try {
            String combineKey = getCombineKey(rateLimiter, point);
            List<String> keys = Collections.singletonList(combineKey);
            number = redisTemplate.execute(limitScript, keys, count, time);
        } catch (Exception e) {
            throw new ResultError(ResultOk.CODE_ERROR, "访问过于频繁，请稍候再试");
        }
        if (number == null || number.intValue() > count) {
            throw new ResultError(ResultOk.CODE_ERROR, "访问过于频繁，请稍候再试");
        }
    }

    /**
     * 组合key
     *
     * @param rateLimiter 限流 对象
     * @param point       切点
     * @return String
     */
    public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) {
        StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
        if (rateLimiter.limitType() == LimitType.IP) {
            stringBuffer.append(IpUtil.getIP(IpUtil.getRequest())).append("-");
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
        return stringBuffer.toString();
    }
}
